﻿using DMSkin.WPF;
using log4net;
using MXComponent.Api;
using MXComponent.Common.Utility;
using MXComponent.DAL;
using MXComponent.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace MXComponent.Views.materialwarehouse
{
    /// <summary>
    /// materialwarehousePage.xaml 的交互逻辑
    /// </summary>
    public partial class materialwarehousePage : DMSkinSimpleWindow
    {
        public static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private AxActUtlTypeLib.AxActUtlType axActUtlType = null;
        public materialwarehousePage()
        {
            InitializeComponent();
            axActUtlType = new AxActUtlTypeLib.AxActUtlType();
            WindowsFormsHost1.Child = axActUtlType;
            DataSet ds = mwdb.GetList("H.active=1");
            if (ds.Tables != null && ds.Tables.Count > 0)
            {
                this.txtWarehouseno.Value = ds.Tables[0].Rows.Count + 1;
            }
            this.btnok.IsEnabled = GlobalClass.user.IsSystem;
            BindMaterial();
        }

        private materialDB mdb = new materialDB();
        private materialwarehouseDB mwdb = new materialwarehouseDB();
        private int? warehouseid = null;

        public materialwarehousePage(int warehouseid)
        {
            InitializeComponent();
            BindMaterial();
            //Hide();
            axActUtlType = new AxActUtlTypeLib.AxActUtlType();
            WindowsFormsHost1.Child = axActUtlType;
            this.warehouseid = warehouseid;
            materialwarehouseData mwmodel = mwdb.GetModel(warehouseid);
            this.txtWarehouseno.Value = mwmodel.warehouseno;
            this.txtWarehouseno.IsEnabled = false;
            this.txtWarehousename.Text = mwmodel.warehousename;
            this.txtHighspeed.Text = mwmodel.highspeed.ToString();
            this.txtDJHighspeed.Text = mwmodel.djhighspeed.ToString();
            this.txtMediumspeed.Text = mwmodel.mediumspeed.ToString();
            this.txtLowspeed.Text = mwmodel.lowspeed.ToString();
            this.txtDJLowspeed.Text = mwmodel.djlowspeed.ToString();
            this.txtDJMediumsspeed.Text = mwmodel.djmediumspeed.ToString();
            this.txtBeforeclose.Text = mwmodel.beforeclose.ToString();
            this.txtContacttime.Text = mwmodel.contacttime.ToString();
            this.txtWarehousename.Text = mwmodel.warehousename;
            this.cbbMaterialname.SelectedValue = mwmodel.materialid;
            this.txtHighspeedPLC.Text = mwmodel.highspeedplc == null ? string.Empty : mwmodel.highspeedplc.ToString();
            this.txtDJHighspeedPLC.Text = mwmodel.djhighspeedplc == null ? string.Empty : mwmodel.djhighspeedplc.ToString();
            this.txtMediumspeedPLC.Text = mwmodel.mediumspeedplc == null ? string.Empty : mwmodel.mediumspeedplc.ToString();
            this.txtLowspeedPLC.Text = mwmodel.lowspeedplc == null ? string.Empty : mwmodel.lowspeedplc.ToString();
            this.txtDJLowspeedPLC.Text = mwmodel.djlowspeedplc == null ? string.Empty : mwmodel.djlowspeedplc.ToString();
            this.txtDJMediumsspeedPLC.Text = mwmodel.djmediumspeedplc == null ? string.Empty : mwmodel.djmediumspeedplc.ToString();
            this.txtBeforeclosePLC.Text = mwmodel.beforecloseplc == null ? string.Empty : mwmodel.beforecloseplc.ToString();
            this.txtContacttimePLC.Text = mwmodel.contacttimeplc == null ? string.Empty : mwmodel.contacttimeplc.ToString();
            this.txtPlanqtyPLC.Text = mwmodel.planqtyplc == null ? string.Empty : mwmodel.planqtyplc.ToString();
            this.txtErrorqtyPLC.Text = mwmodel.errorqtyplc == null ? string.Empty : mwmodel.errorqtyplc.ToString();
            this.txtRealqtyPLC.Text = mwmodel.realqtyplc == null ? string.Empty : mwmodel.realqtyplc.ToString();
            this.txtSaveFlagPLC.Text = mwmodel.saveflagplc == null ? string.Empty : mwmodel.saveflagplc.ToString();
            //this.txtStatusPLC.Text = mwmodel.statusplc == null ? string.Empty : mwmodel.statusplc.ToString();
            //this.txtFinishCountPLC.Text = mwmodel.finishcountplc == null ? string.Empty : mwmodel.finishcountplc.ToString();
            this.btnok.IsEnabled = GlobalClass.user.IsSystem;
        }

        private void Btnok_Click(object sender, RoutedEventArgs e)
        {
            //if (string.IsNullOrWhiteSpace(this.txtWarehouseno.Value))
            //{
            //    MessageBox.Show("物料编码不能为空！");
            //    this.txtMaterialcode.Focus();
            //    return;
            //}
            List<string> plcList = new List<string>();
            List<short> valueList = new List<short>();
            if (this.warehouseid == null)
            {
                DataSet ds = mwdb.GetList(" H.active=1 and warehouseno=" + this.txtWarehouseno.Value);
                if (ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    MessageBox.Show("料仓编号不能重复！");
                    this.txtWarehouseno.Focus();
                    return;
                }
            }
            if (string.IsNullOrWhiteSpace(this.cbbMaterialname.Text))
            {
                MessageBox.Show("物料不能为空！");
                this.cbbMaterialname.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(this.txtWarehousename.Text))
            {
                MessageBox.Show("料仓名称不能为空！");
                this.txtWarehousename.Focus();
                return;
            }
            //if (string.IsNullOrWhiteSpace(this.txtStatusPLC.Text))
            //{
            //    MessageBox.Show("料仓状态PLC地址不能为空！");
            //    this.txtStatusPLC.Focus();
            //    return;
            //}
            //if (string.IsNullOrWhiteSpace(this.txtFinishCountPLC.Text))
            //{
            //    MessageBox.Show("料仓完成数量PLC地址不能为空！");
            //    this.txtFinishCountPLC.Focus();
            //    return;
            //}
            //if (string.IsNullOrWhiteSpace(this.txtStatusPLC.Text))
            //{
            //    MessageBox.Show("料仓状态PLC地址不能为空！");
            //    this.txtStatusPLC.Focus();
            //    return;
            //}
            if (string.IsNullOrWhiteSpace(this.txtPlanqtyPLC.Text))
            {
                MessageBox.Show("设定重量PLC地址不能为空！");
                this.txtPlanqtyPLC.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(this.txtErrorqtyPLC.Text))
            {
                MessageBox.Show("设定误差PLC地址不能为空！");
                this.txtErrorqtyPLC.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(this.txtRealqtyPLC.Text))
            {
                MessageBox.Show("实际重量PLC地址不能为空！");
                this.txtRealqtyPLC.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(this.txtSaveFlagPLC.Text))
            {
                MessageBox.Show("存盘PLC地址不能为空！");
                this.txtSaveFlagPLC.Focus();
                return;
            }
            try
            {
                materialwarehouseData mwmodel = new materialwarehouseData();
                mwmodel.active = 1;
                mwmodel.warehouseno = this.txtWarehouseno.Value;
                mwmodel.materialid = Int32.Parse(this.cbbMaterialname.SelectedValue.ToString());
                mwmodel.statusplc = string.Empty;
                mwmodel.finishcountplc = string.Empty;
                //mwmodel.statusplc = this.txtStatusPLC.Text.Trim();
                //mwmodel.finishcountplc = this.txtFinishCountPLC.Text.Trim();
                mwmodel.planqtyplc = this.txtPlanqtyPLC.Text.Trim().ToUpper();
                mwmodel.errorqtyplc = this.txtErrorqtyPLC.Text.Trim().ToUpper();
                mwmodel.realqtyplc = this.txtRealqtyPLC.Text.Trim().ToUpper();
                mwmodel.saveflagplc = this.txtSaveFlagPLC.Text.Trim().ToUpper();

                if (!string.IsNullOrWhiteSpace(this.txtHighspeed.Text))
                {
                    if (!Validator.IsNumber(this.txtHighspeed.Text))
                    {
                        MessageBox.Show("高速只能是整数类型！");
                        this.txtHighspeed.SelectAll();
                        this.txtHighspeed.Focus();
                        return;
                    }
                    mwmodel.highspeed = Int32.Parse(this.txtHighspeed.Text.Trim());
                    valueList.Add(Convert.ToInt16(mwmodel.highspeed));
                    if (string.IsNullOrWhiteSpace(this.txtHighspeedPLC.Text))
                    {
                        MessageBox.Show("高速PLC地址不能为空！");
                        this.txtHighspeedPLC.Focus();
                        return;
                    }
                    mwmodel.highspeedplc = this.txtHighspeedPLC.Text.Trim().ToUpper();
                    plcList.Add(mwmodel.highspeedplc);
                }
                if (!string.IsNullOrWhiteSpace(this.txtDJHighspeed.Text))
                {
                    if (!Validator.IsNumber(this.txtDJHighspeed.Text))
                    {
                        MessageBox.Show("电机高速只能是整数类型！");
                        this.txtDJHighspeed.SelectAll();
                        this.txtDJHighspeed.Focus();
                        return;
                    }
                    mwmodel.djhighspeed = Int32.Parse(this.txtDJHighspeed.Text.Trim());
                    valueList.Add(Convert.ToInt16(mwmodel.djhighspeed));
                    if (string.IsNullOrWhiteSpace(this.txtDJHighspeedPLC.Text))
                    {
                        MessageBox.Show("电机高速PLC地址不能为空！");
                        this.txtDJHighspeedPLC.Focus();
                        return;
                    }
                    mwmodel.djhighspeedplc = this.txtDJHighspeedPLC.Text.Trim().ToUpper();
                    plcList.Add(mwmodel.djhighspeedplc);
                }
                if (!string.IsNullOrWhiteSpace(this.txtMediumspeed.Text))
                {
                    if (!Validator.IsNumber(this.txtMediumspeed.Text))
                    {
                        MessageBox.Show("中速只能是整数类型！");
                        this.txtMediumspeed.SelectAll();
                        this.txtMediumspeed.Focus();
                        return;
                    }
                    mwmodel.mediumspeed = Int32.Parse(this.txtMediumspeed.Text.Trim());
                    valueList.Add(Convert.ToInt16(mwmodel.mediumspeed));
                    if (string.IsNullOrWhiteSpace(this.txtMediumspeedPLC.Text))
                    {
                        MessageBox.Show("中速PLC地址不能为空！");
                        this.txtMediumspeedPLC.Focus();
                        return;
                    }
                    mwmodel.mediumspeedplc = this.txtMediumspeedPLC.Text.Trim().ToUpper();
                    plcList.Add(mwmodel.mediumspeedplc);
                }
                if (!string.IsNullOrWhiteSpace(this.txtLowspeed.Text))
                {
                    if (!Validator.IsNumber(this.txtLowspeed.Text))
                    {
                        MessageBox.Show("低速只能是整数类型！");
                        this.txtLowspeed.SelectAll();
                        this.txtLowspeed.Focus();
                        return;
                    }
                    mwmodel.lowspeed = Int32.Parse(this.txtLowspeed.Text.Trim());
                    valueList.Add(Convert.ToInt16(mwmodel.lowspeed));
                    if (string.IsNullOrWhiteSpace(this.txtLowspeedPLC.Text))
                    {
                        MessageBox.Show("低速PLC地址不能为空！");
                        this.txtLowspeedPLC.Focus();
                        return;
                    }
                    mwmodel.lowspeedplc = this.txtLowspeedPLC.Text.Trim().ToUpper();
                    plcList.Add(mwmodel.lowspeedplc);
                }
                if (!string.IsNullOrWhiteSpace(this.txtDJLowspeed.Text))
                {
                    if (!Validator.IsNumber(this.txtDJLowspeed.Text))
                    {
                        MessageBox.Show("电机低速只能是整数类型！");
                        this.txtDJLowspeed.SelectAll();
                        this.txtDJLowspeed.Focus();
                        return;
                    }
                    mwmodel.djlowspeed = Int32.Parse(this.txtDJLowspeed.Text.Trim());
                    valueList.Add(Convert.ToInt16(mwmodel.djlowspeed));
                    if (string.IsNullOrWhiteSpace(this.txtDJLowspeedPLC.Text))
                    {
                        MessageBox.Show("电机低速PLC地址不能为空！");
                        this.txtDJLowspeedPLC.Focus();
                        return;
                    }
                    mwmodel.djlowspeedplc = this.txtDJLowspeedPLC.Text.Trim().ToUpper();
                    plcList.Add(mwmodel.djlowspeedplc);
                }
                if (!string.IsNullOrWhiteSpace(this.txtDJMediumsspeed.Text))
                {
                    if (!Validator.IsNumber(this.txtDJMediumsspeed.Text))
                    {
                        MessageBox.Show("电机中速只能是整数类型！");
                        this.txtDJMediumsspeed.SelectAll();
                        this.txtDJMediumsspeed.Focus();
                        return;
                    }
                    mwmodel.djmediumspeed = Int32.Parse(this.txtDJMediumsspeed.Text.Trim());
                    valueList.Add(Convert.ToInt16(mwmodel.djmediumspeed));
                    if (string.IsNullOrWhiteSpace(this.txtDJMediumsspeedPLC.Text))
                    {
                        MessageBox.Show("电机中速PLC地址不能为空！");
                        this.txtDJMediumsspeedPLC.Focus();
                        return;
                    }
                    mwmodel.djmediumspeedplc = this.txtDJMediumsspeedPLC.Text.Trim().ToUpper();
                    plcList.Add(mwmodel.djmediumspeedplc);
                }
                if (!string.IsNullOrWhiteSpace(this.txtBeforeclose.Text))
                {
                    if (!Validator.IsNumber(this.txtBeforeclose.Text))
                    {
                        MessageBox.Show("预关门只能是整数类型！");
                        this.txtBeforeclose.SelectAll();
                        this.txtBeforeclose.Focus();
                        return;
                    }
                    mwmodel.beforeclose = Int32.Parse(this.txtBeforeclose.Text.Trim());
                    valueList.Add(Convert.ToInt16(mwmodel.beforeclose));
                    if (string.IsNullOrWhiteSpace(this.txtBeforeclosePLC.Text))
                    {
                        MessageBox.Show("预关门PLC地址不能为空！");
                        this.txtBeforeclosePLC.Focus();
                        return;
                    }
                    mwmodel.beforecloseplc = this.txtBeforeclosePLC.Text.Trim().ToUpper();
                    plcList.Add(mwmodel.beforecloseplc);
                }
                if (!string.IsNullOrWhiteSpace(this.txtContacttime.Text))
                {
                    if (!Validator.IsNumber(this.txtContacttime.Text))
                    {
                        MessageBox.Show("点动时间只能是整数类型！");
                        this.txtContacttime.SelectAll();
                        this.txtContacttime.Focus();
                        return;
                    }
                    mwmodel.contacttime = Int32.Parse(this.txtContacttime.Text.Trim());
                    valueList.Add(Convert.ToInt16(mwmodel.contacttime));
                    if (string.IsNullOrWhiteSpace(this.txtContacttimePLC.Text))
                    {
                        MessageBox.Show("点动时间PLC地址不能为空！");
                        this.txtContacttimePLC.Focus();
                        return;
                    }
                    mwmodel.contacttimeplc = this.txtContacttimePLC.Text.Trim().ToUpper();
                    plcList.Add(mwmodel.contacttimeplc);
                }
                mwmodel.warehousename = this.txtWarehousename.Text.Trim();

                //连接后，返回的结果
                int iReturnCode;
                if (plcList != null && plcList.Count > 0)
                {
                    //不加这三句会报
                    //引发类型为“System.Windows.Forms.AxHost+InvalidActiveXStateException”的异常
                    ((System.ComponentModel.ISupportInitialize)(axActUtlType)).BeginInit();
                    ((System.ComponentModel.ISupportInitialize)(axActUtlType)).EndInit();
                    axActUtlType.ActLogicalStationNumber = PLCClass.iLogicalStationNumber; ;

                    //设置口令
                    axActUtlType.ActPassword = "";


                    //执行打开口令，并将返回值赋给iReturnCode
                    iReturnCode = axActUtlType.Open();
                    if (iReturnCode == 0)
                    {
                        short[] valueArray = valueList.ToArray();
                        iReturnCode = axActUtlType.WriteDeviceRandom2(string.Join("\n", plcList), valueArray.Length, ref valueArray[0]);
                        if (iReturnCode != 0)
                        {
                            MessageBox.Show("PLC写入失败！");
                            return;
                        }
                        if (this.warehouseid != null)
                        {
                            mwmodel.warehouseid = int.Parse(this.warehouseid.ToString());
                            mwmodel.updateby = GlobalClass.user.userid;
                            mwmodel.updatetime = DateTime.Now.ToString();
                            mwdb.ModifyRecord(mwmodel);
                        }
                        else
                        {
                            mwmodel.creatby = GlobalClass.user.userid;
                            mwmodel.createtime = DateTime.Now.ToString();
                            mwdb.AddRecord(mwmodel);
                        }
                        MessageBox.Show("保存成功!");
                    }
                    else
                    {
                        MessageBox.Show("连接PLC失败！");
                        return;
                    }
                }
                else
                {
                    if (this.warehouseid != null)
                    {
                        mwmodel.warehouseid = int.Parse(this.warehouseid.ToString());
                        mwmodel.updateby = GlobalClass.user.userid;
                        mwmodel.updatetime = DateTime.Now.ToString();
                        mwdb.ModifyRecord(mwmodel);
                    }
                    else
                    {
                        mwmodel.creatby = GlobalClass.user.userid;
                        mwmodel.createtime = DateTime.Now.ToString();
                        mwdb.AddRecord(mwmodel);
                    }
                    MessageBox.Show("保存成功!");
                }
                
                this.DialogResult = true;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                MessageBox.Show(ex.Message);
            }
        }

        private void Btnclose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 只限数字输入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("[^0-9.-]+");
            e.Handled = re.IsMatch(e.Text);
        }

        private void BindMaterial()
        {
            string str = " active=1";
            DataSet ds = mdb.GetList(str);
            this.cbbMaterialname.ItemsSource = ds.Tables[0].DefaultView;
            this.cbbMaterialname.DisplayMemberPath = "materialname";
            this.cbbMaterialname.SelectedValuePath = "materialid";
        }

        private void DMSkinSimpleWindow_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void DMSkinSimpleWindow_Closed(object sender, EventArgs e)
        {
            axActUtlType.Close();
        }

        private void Hide()
        {
            txtHighspeedPLC.Visibility = Visibility.Hidden;
            txtMediumspeedPLC.Visibility = Visibility.Hidden;
            txtLowspeedPLC.Visibility = Visibility.Hidden;
            txtBeforeclosePLC.Visibility = Visibility.Hidden;
            txtContacttimePLC.Visibility = Visibility.Hidden;
            txtPlanqtyPLC.Visibility = Visibility.Hidden;
            txtErrorqtyPLC.Visibility = Visibility.Hidden;
            txtRealqtyPLC.Visibility = Visibility.Hidden;
            txtSaveFlagPLC.Visibility = Visibility.Hidden;
            txtDJHighspeedPLC.Visibility = Visibility.Hidden;
            txtDJLowspeedPLC.Visibility = Visibility.Hidden;
            txtDJMediumsspeedPLC.Visibility = Visibility.Hidden;
        }
    }
}